package com.huatec.hiot_cloud.core.dao.impl;

import com.huatec.hiot_cloud.core.dao.IMongoDBBaseDao;
import com.huatec.hiot_cloud.core.mongo_spring.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

public class MongoDBUserDaoImpl implements IMongoDBBaseDao<User> {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void createCollection() {
        if (!mongoTemplate.collectionExists(User.class)){
            mongoTemplate.createCollection(User.class);
        }
    }

    @Override
    public void insert(User entity) {
        mongoTemplate.insert(entity);
    }

    @Override
    public User findById(String id) {
        return mongoTemplate.findById(id,User.class);
    }

    @Override
    public List<User> findList(Integer skip, Integer limit) {
        Query query = new Query();
        query.skip(skip).limit(limit);
        return this.mongoTemplate.find(query, User.class);
    }

    @Override
    public List<User> findListByStr(String str) {
        Query query = new Query();
        Criteria criteria = new Criteria("username").is(str);
        query.addCriteria(criteria);
        return this.mongoTemplate.find(query, User.class);
    }

    @Override
    public void update(User entity) {
        //新建查询容器
        Query query = new Query();
        //新建查询条件
        Criteria criteria = new Criteria("_id").is(entity.getId());
        //组合查询容器和条件
        query.addCriteria(criteria);
        //新建更新容器
        Update update = new Update();
        //添加更新容器内容
        update.set("username",entity.getUsername());
        update.set("age",entity.getAge());
        //调用mongodb查询模版 执行更新语句
        this.mongoTemplate.updateFirst(query,update,User.class);
    }

    @Override
    public void delete(User entity) {
        Query query = new Query();
        Criteria criteria = new Criteria("_id").is(entity.getId());
        query.addCriteria(criteria);
        this.mongoTemplate.findAllAndRemove(query,User.class);
    }
}
